package frog.lazy.framework.keeper.filter;

import frog.lazy.framework.core.exception.BizException;
import frog.lazy.framework.core.tools.StrUtils;
import frog.lazy.framework.keeper.constant.JWTConstant;
import frog.lazy.framework.keeper.provider.IAccountProvider;
import frog.lazy.framework.keeper.utils.JWTUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 *   基于 用户名密码 的认证过滤器
 * @date 20:18 2018/2/10
 */
@Slf4j
@AllArgsConstructor
public class PasswordFilter extends AccessControlFilter {

    private JWTUtils jwtUtils;
    private IAccountProvider accountProvider;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//        Subject subject = getSubject(request,response);
        HttpServletRequest req = (HttpServletRequest) request;
        if("OPTIONS".equals(req.getMethod())) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(JWTConstant.header_token);
        if(StrUtils.isNotBlank(token)) {
            return accountProvider.check(jwtUtils.parseJwt(token));
        }
        throw BizException.noLogin("没有登录");
    }
}
